<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="id"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.carouselFigureId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播文章">
        <template slot-scope="scope">
          <span>{{ scope.row.articleTitle }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播图片">
        <template slot-scope="scope">
          <a :href="scope.row.carouselFigureImage" target="_blank" v-if="scope.row.carouselFigureImage"><img :src="scope.row.carouselFigureImage" style="width: 60px;"></a>
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="时间">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding">
        <template slot-scope="{row}">
          <el-button type="primary" size="small" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.carouselFigureId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="轮播图片（16:9）：" prop="carouselFigureImage">
          <el-upload
            list-type="picture-card"
            class="avatar-uploader"
            action="/v2/editor/image"
            :show-file-list="false"
            :headers="headers"
            :on-success="onCarouselFigureImageUploadSuccess"
            :before-upload="beforeCarouselFigureImageUpload"
          >
            <img v-if="temp.carouselFigureImage" :src="temp.carouselFigureImage" width="100%" >
            <i v-else class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播文章：" prop="articleId">
          <el-select v-model="temp.articleId" class="filter-item" placeholder="请选择轮播文章">
            <el-option v-for="item in articleOptions" :key="item.articleId" :label="item.articleTitle" :value="item.articleId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAccessToken } from '@/utils/auth'
import { fetchCarouselFigureList, fetchListCount, saveCarouselFigure, deleteCarouselFigure } from '@/api/carouselFigure'
import { fetchList } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'HazardTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    stateStyleFilter(stateCode) {
      const styleMap = {
        '0': 'success',
        '1': 'warning'
      }
      return styleMap[stateCode]
    },
    parseTime: parseTime
  },
  data() {
    return {
      headers: {
        'accessToken': getAccessToken()
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        size: 20
      },
      articleOptions: [
      ],
      temp: {
        articleId: '',
        carouselFigureImage: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑轮播图',
        create: '新建轮播图'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        articleId: [{ required: true, message: '轮播文章不得为空', trigger: 'change' }],
        carouselFigureImage: [{ required: true, message: '轮播图片不得为空', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    fetchList({ page: 1, size: 99999999 }).then(response => {
      this.articleOptions = response.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchListCount(this.listQuery).then(response => {
        this.total = response.data
      })
      fetchCarouselFigureList(this.listQuery).then(response => {
        // hack 后端修改数据格式
        this.list = response.data

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        articleId: '',
        carouselFigureImage: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveCarouselFigure(this.temp).then((response) => {
            // this.total += 1
            // if (this.total < this.listQuery.size) {
            //   this.list.push(response.data) // 只有当总数小于limit才显示在本页面上
            // }
            this.dialogFormVisible = false
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '添加轮播图成功',
              type: 'success',
              duration: 2000,
              onClose: () => {
                location.reload()
              }
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          saveCarouselFigure(tempData).then(() => {
            for (const v of this.list) {
              if (v.carouselFigureId === this.temp.carouselFigureId) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '提示',
              message: '修改轮播图成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(carouselFigureId) {
      const message = '确定要删除该轮播图吗？'
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCarouselFigure(carouselFigureId).then(() => {
          this.$notify({
            title: '提示',
            message: '删除成功',
            type: 'success',
            duration: 2000,
            onClose: () => {
              location.reload()
            }
          })
        })
      })
    },
    onCarouselFigureImageUploadSuccess(res, file) {
      this.temp.carouselFigureImage = res.data.src
      // console.log(res)
    },
    beforeCarouselFigureImageUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!(isJPG || isPNG)) {
        this.$message.error('上传的轮播图片只能是jpg或png格式')
      }
      // var windowURL = window.URL || window.webkitURL
      // this.temp.avatarUrl = windowURL.createObjectURL(file)
      // if (!isLt2M) {
      //   this.$message.error('上传的头像图片大小不能超过2MB')
      // }
      return (isJPG || isPNG) && isLt2M
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
